#include "friendlist.h"
#include "ui_friendlist.h"
#include "changepersonalinfo.h"
#include "addfriendsender.h"
#include "addfriendreceiver.h"
#include "addfriendsearch.h"
#include "user.h"
#include <QHostAddress>
#include <QMessageBox>

void friendlist::closeEvent(QCloseEvent *)
{
    emit this->closefriendlistWidget();
}

friendlist::friendlist(QWidget *parent, user userSelf) :
    QWidget(parent),
    ui(new Ui::friendlist)
{
    ui->setupUi(this);
    this->userSelf = userSelf;
    this->setWindowTitle("好友列表");//添加标题
    ui->textBrowser_name->append(userSelf.getUserName());//在界面添加个人信息
    ui->textBrowser_id->append(userSelf.getUserId());
    ui->textBrowser_gender->append(userSelf.getUserGender());
    ui->frame_photo->setStyleSheet("background-image:url("/*这里插入图片地址*/") ");
    //ui->messageSendTextEdit->clear();
    this->close();
    socket = new QWebSocket();//新建websocket


    //向后端发送信息
    //QNetworkRequest request(QUrl("http://localhost:19999/slimarveous/get_friend_list"));
    QNetworkRequest request(QUrl("http://101.43.168.188:19999/slimarveous/get_friend_list"));//获取http地址




    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json2");//设置传输文件
    QJsonObject json2{
        {"id",userSelf.getUserId().toInt()},
        {"username", userSelf.getUserName()},
        {"token", userSelf.getUserPassword()}
    };
    QJsonDocument doc(json2);
    QByteArray data = doc.toJson(QJsonDocument::Compact);//传输文件
    QNetworkReply *reply = manager.post(request, data);//获取http回复
    //QString message;
    //连接服务，处理相应数据
    connect(reply, &QNetworkReply::finished, [=]()
    {
        if (reply->error() == QNetworkReply::NoError)
        {
            // 读取响应数据
            QByteArray dataReply = reply->readAll();
            // 将 JSON 数据转换为 QVariant 对象
            QJsonParseError error;
            QJsonObject result = QJsonDocument::fromJson(dataReply, &error).object();
            //qDebug()<<result;
            // 处理 JSON 数据
            if(error.error == QJsonParseError::NoError)
            {
                QVariantMap resultMap = result.toVariantMap();

                //提取状态码
                QVariant status_code = resultMap.value("status_code");
                status_code.toString();
                QJsonArray friendList = resultMap.value("friends").toJsonArray();//处理好友的序列
                bool messageStatus[friendList.size()];//好友序列阅读消息状态
                for (int i = 0; i < friendList.size(); i++)
                {
                    messageStatus[i] = 0;
                }
                QLabel* ucMessageLabel = new QLabel[friendList.size()];
                for(int i = 0; i < friendList.size(); i++)//循环添加好友列表
                {
                    QJsonObject friendMap = friendList.at(i).toObject();
                    QVariant friendName = friendMap.value("username");
                    QVariant friendId = friendMap.value("id");
                    QVariant friendGender = friendMap.value("gender");
                    QVariant friendPhoto = friendMap.value("photo");

                    QPushButton *friendButton = new QPushButton(friendName.toString(), this);//创建好友按钮
                    //为每个好友按钮设置一个未读消息label
                    ucMessageLabel[i].setParent(friendButton);
                    ucMessageLabel[i].move(350,8);//设置坐标
                    ucMessageLabel[i].resize(15, 15);//设置大小
                    ucMessageLabel[i].setStyleSheet("border-radius: 50%; background-color: red; ");
                    ucMessageLabel[i].setAlignment(Qt::AlignCenter);
                    ucMessageLabel[i].hide();
                    for(int j = 0; j < messageQueue.size(); j++)
                    {
                        if(messageQueue[j].messageSender == friendName.toString())
                            ucMessageLabel[i].show();
                    }

                    QListWidgetItem *item = new QListWidgetItem(ui->listWidget_friend);//创建一个好友项
                    item->setSizeHint(friendButton->sizeHint()); // 设置列表项的大小
                    ui->listWidget_friend->setItemWidget(item, friendButton); // 将按钮控件添加到列表项中

                    //接受信息就显示红点
                    QObject::connect(socket, &QWebSocket::textMessageReceived, [=](const QString &message)
                    {
                        QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8());
                        QJsonObject obj = doc.object();
                        QString type = obj.value("type").toString();//传到服务器后端的类型type参数
                        //类型为chat
                        if (type == "chat")//如果为实时聊天
                        {
                            QVariantMap messageMap = obj.toVariantMap();//处理当时发送的消息
                            QMap senderMap = messageMap.value("sender").toMap();
                            QVariant senderName = senderMap.value("username");
                            if(senderName.toString() == friendName.toString())
                            {
                                ucMessageLabel[i].show();
                            }
                        }
                    });

                    // 在这里处理和该好友对话的逻辑
                    connect(friendButton, &QPushButton::clicked, this,[=]() {
                        ucMessageLabel[i].hide();
                        //创建新的聊天窗口
                        MainInterfaceWidget* mainWindow = new MainInterfaceWidget(nullptr, userSelf, friendName.toString(), friendId.toInt(), socket);
                        mainWindow->setWindowTitle(friendName.toString());
                        mainWindow->setWindowIcon(QIcon(friendPhoto.toString()));
                        mainWindow->show();
                    });
                }

            }
        }
        else//出现问题
            qDebug()<<"error";
        reply->deleteLater();
    });

    connect(ui->addfriendsender,&QPushButton::clicked,this, &friendlist::addfriendsender_clicked);//好友添加
    connect(ui->addfriendsearch,&QPushButton::clicked,this, &friendlist::addfriendsearch_clicked);//好友搜索





    //QUrl url("ws://localhost:19999/slimarveous/ws");
    QUrl url("ws://101.43.168.188:19999/slimarveous/ws");//连接websocket地址



    QUrlQuery query;//在query里面添加id token两个信息，进而访问后端信息
    query.addQueryItem("id",userSelf.getUserId());
    query.addQueryItem("token",userSelf.getUserPassword());
    url.setQuery(query);
    socket->open(url);
    //连接到server
    QObject::connect(socket, &QWebSocket::connected,[=]()
    {
        qDebug() << "WebSocket connected";
    });
    //断开链接
    connect(this, &friendlist::closefriendlistWidget,this,[=](){
        socket->close();
    });
    QObject::connect(socket, &QWebSocket::disconnected, [=]()
    {
        qDebug() << "WebSocket disconnected";
    });

    //获取信息
    QObject::connect(socket, &QWebSocket::textMessageReceived, [=](const QString &message)
    {
        //接收信息
        QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8());
        //doc转换成json
        QJsonObject obj = doc.object();
        //分析接收到的服务器信息类型
        QString type = obj.value("type").toString();//传到服务器后端的类型type参数
        //类型为chat
        if (type == "chat")//如果为实时聊天
        {
            QVariantMap messageMap = obj.toVariantMap();//处理当时发送的消息
            QMap senderMap = messageMap.value("sender").toMap();
            QVariant senderName = senderMap.value("username");
            int senderId = senderMap.value("id").toInt();
            QString receivedContent = obj.value("content").toString();
            QString receivedTime = obj.value("time").toString();
            qDebug() << "发送者的id:" << senderId;

            Message chatMessage
            {
                this->userSelf.getUserName(),
                this->userSelf.getUserId().toInt(),
                receivedTime,
                senderName.toString(),
                senderId,
                receivedContent
            };

            messageQueue.append(chatMessage);//添加到聊天处理队列里面
        }
        //类型为未读消息
        else if (type == "pull_chat")
        {
            //将未读消息json文件转化成map

            QVariantMap pullChatMap = obj.toVariantMap();
            QJsonArray ucMsg = pullChatMap.value("uc_messages").toJsonArray();
            for(int i = 0; i < ucMsg.size(); i++)
            {
                QJsonObject ucJsonObj = ucMsg.at(i).toObject();
                QVariantMap messageMap = ucJsonObj.toVariantMap();
                QMap senderMap = messageMap.value("sender").toMap();
                QVariant senderName = senderMap.value("username");
                int senderId = senderMap.value("id").toInt();
                QString ucMsgContent = ucJsonObj.value("content").toString();
                QString ucMsgTime = ucJsonObj.value("time").toString();
                //qDebug() << ucJsonObj;
                Message ucMessage{this->userSelf.getUserName(), this->userSelf.getUserId().toInt(), ucMsgTime, senderName.toString(), senderId, ucMsgContent};
                messageQueue.append(ucMessage);
            }
        }
        else if (type == "add_friend")//接收到添加好友请求
        {
            QVariantMap messageMap = obj.toVariantMap();//处理信息
            cout<<"efsdf"<<endl;
            addfriendreceiver *afr = new addfriendreceiver(nullptr, userSelf,messageMap,socket);
            afr->show();
            //下面开始打印信息
        }
        else if (type=="add_friend_fail_or_success")//在B同意或拒绝时处理数据，如果同意对双方发送消息，如果拒绝只对A发消息
        {
            QVariantMap messageMap = obj.toVariantMap();
            QMap receiverMap = messageMap.value("the_other").toMap();
            QVariant receiverName = receiverMap.value("username");
            QString add_friend_fail_or_success=obj.value("add_friend_fail_or_success").toString();
            QString message=obj.value("message").toString();
            QMessageBox:: information(this, "你向"+receiverName.toString()+"好友请求",message);//提示弹窗
        }
        else if (type == "pull_friend_req")//离线处理好友请求
        {
            //将未读消息json文件转化成map
            QVariantMap pullChatMap = obj.toVariantMap();
            QJsonArray reqQueue = pullChatMap.value("req_queue").toJsonArray();//转化为队列，处理请求
            for(int i = 0; i < reqQueue.size(); i++)
            {
                QJsonObject reqJsonObj = reqQueue.at(i).toObject();//转化为object
                QVariantMap messageMap = reqJsonObj.toVariantMap();//转化为map发送后端
                addfriendreceiver *afr = new addfriendreceiver(nullptr, userSelf,messageMap,socket);//调用receiver
                afr->show();
            }
        }
    });
}

friendlist::~friendlist()
{
    delete ui;
}

//修改个人信息
void friendlist::on_toolButton_infChange_clicked()
{
    this->close();
    changepersonalinfo *cpi=new changepersonalinfo(nullptr,userSelf);
    cpi->show();
}
void friendlist::addfriendsender_clicked()
{
    addfriendsender *afs = new addfriendsender(nullptr, userSelf);
    afs->show();
}
void friendlist:: addfriendsearch_clicked()
{
    addfriendsearch *afsr = new addfriendsearch(nullptr, userSelf);
    afsr->show();
}
